import React from 'react';

export default function index() {
  // 1\旋转数组
  const rotetaArray = (arr = [], num = 0) => {
    const infontArr = arr.slice(0, num);
    const rotetaArr = arr.splice(num);
    return [...rotetaArr, ...infontArr];
  };

  const roArr = rotetaArray([1, 2, 3, 4, 5, 6], 3);
  console.log(roArr);
  // 2\对称数字
  const symmetryNumber = () => {
    let a = [];
    for (let i = 1; i < 1000; i++) {
      if (i.toString().split('').reverse().join('') == i && i / 10 > 1) {
        a.push(i);
      }
    }
    return a;
  };
  console.log(symmetryNumber());

  // 3\双指针实现将数组中的0移到末尾
  const removeArray = (arr = []) => {
    let point0 = 0; // 慢指针记录第一个0的位置
    let i = 0; // 快指针 遍历数组
    for (; i < arr.length; i++) {
      if (arr[i] == 0 && arr[point0] != 0) {
        point0 = i;
      } else if (point0 < i && arr[i] != 0 && arr[point0] == 0) {
        const temp = arr[i]; //将0往后移动
        arr[i] = arr[point0];
        arr[point0] = temp;
        point0 = i;
      }
    }
    return arr;
  };

  function afterZeroFn3(arr) {
    let point1 = 0;
    let i = 0;
    for (; i < arr.length; i++) {
      if (arr[i] != 0) {
        if (arr[point1] == 0) {
          arr[point1] = arr[i];
          arr[i] = 0;
        }
        point1++;
      }
    }
    return arr;
  }

  //4\将传入的数字逆序字符串
  const reverseNumber = (num = 0) => {
    // 1、toString转为字符串
    // 2、split 字符串转为子字符串数组
    // 3、reverse 倒转数组
    // 4、join 转为字符串，添加‘’分隔
    return num.toString().split('').reverse().join('');
  };

  const reverseNumber2 = (num = 0) => {
    // 递归实现
    const pront = Math.floor(num / 10); // 得到除最后一位的前面n-1位数字
    if (pront == 0) return num % 10; // 终止条件：当前n-1位只有一位数了，即这是数字的第一位
    return [num % 10, reverseNumber2(pront)]; // 每次得到数字的最后一位，继续处理前n-1位
  };

  //5\每次间隔a, a+b, a+2b...a+nb的时间执行fn函数，执行n次欧关闭定时器
  const timeFunction = (fn, a, b, n) => {
    for (let i = 0; i <= n; i++) {
      setTimeout(() => {
        fn();
        console.log(a + i * b);
      }, a + i * b);
    }
  };
  const add = () => {
    console.log(1);
  };

  //   //6\实现Promise.retry
  // Promise.retry = function (fn, times) {
  //   return new Promise(async (resolve, reject) => {
  //     while (true) {
  //       try {
  //         let res = await fn;
  //         resolve(res);
  //         break;
  //       } catch (error) {
  //         if (times < 1) {
  //           reject('fail');
  //           break;
  //         }
  //         times--;
  //         console.log(`第${times}次失败`);
  //       }
  //     }
  //   });
  // };

  // 7、数组扁平化
  const arrFalt = (arr = []) => {
    let result = []; // 记录结果
    arr.forEach((item) => {
      if (Array.isArray(item)) {
        return result.push(...arrFalt(item));
      } else {
        result.push(item);
      }
    });
    return result;
  };
  // 数组去重
  const removeRepeate = (arr = []) => {
    const set = new Set(arr);
    return [...set];
  };
  // 数组排序
  const sortArr = (arr = []) => {
    return arr.sort((a, b) => a - b);
  };
  console.log(arrFalt([1, 2, 5, [2, 3]]));
  console.log(removeRepeate(arrFalt([1, 2, 5, [2, 3]])));
  console.log(sortArr(removeRepeate(arrFalt([1, 2, 5, [2, 3]]))));

  // 8、有下面两个数组
  // [A1, A2, A3, A4, B1, B2, B3, B4, C1, C2, C3, D1]
  // [A, B, C, D]
  // 将他们合并为新的数组：[A1, A2, A3, A4, A, B1, B2, B3, B4, B, C1, C2, C3, C, D1, D]
  const concatArr = () => {
    let arr1 = ['A', 'B', 'C', 'D'];
    let arr2 = [
      'A1',
      'A2',
      'A3',
      'A4',
      'B1',
      'B2',
      'B3',
      'B4',
      'C1',
      'C2',
      'C3',
      'D1',
    ];
    let result = [];
    for (let i = 0; i < arr1.length; i++) {
      for (let j = 0; j < arr2.length; j++) {
        if (arr2[j].startsWith(arr1[i])) {
          result.push(arr2[j]);
        }
      }
      result.push(arr1[i]);
    }
    return result;
  };
  console.log(concatArr());

  // 9、递归查找地点位置
  // 递归函数
  const searchArea = (target, objs) => {
    let result = [];
    const onSearch = (obj, fatherPath = []) => {
      // 每次添加上当前对象的babel以记录路径
      let currentPath = fatherPath.concat(obj.babel);
      // 字符串匹配search，找到该字符串
      if (obj.babel.search(target) != -1) {
        result.push(currentPath);
      }
      if (obj.babel != obj && obj.child) {
        obj.child.map((item) => {
          onSearch(item, currentPath);
        });
      }
    };
    onSearch(objs);
    return result;
  };
  let testObj = {
    babel: '北京市',
    child: [
      {
        babel: '朝阳区',
        child: [
          {
            babel: '西半街道',
          },
          {
            babel: '向上向善',
          },
        ],
      },
      {
        babel: '昌平区',
        child: [
          {
            babel: '香水百合',
          },
          {
            babel: '昌平街道',
          },
        ],
      },
    ],
  };
  console.log(searchArea('香水', testObj));

  const getSize = (target, obj) => {
    // 计算目标文件夹大小
    const sizeSum = (obj) => {
      let totalSize = 0;

      // 目标为文件,直接返回size
      if (obj?.size) {
        totalSize = obj.size;
      } else if (obj?.children?.length > 0) {
        for (const i of obj.children) {
          totalSize += sizeSum(i);
        }
      }
      return totalSize;
    };

    const getTarget = (obj) => {
      // 找到目标
      if (obj.name == target) {
        return obj;
      } else if (obj.name != target && obj.children?.length > 0) {
        for (let i of obj.children) {
          const found = getTarget(i); // 注意每次函数执行后的结果返回到哪里
          if (found) return found;
        }
      }
      return null;
    };

    return sizeSum(getTarget(obj));
  };
  let dir = {
    name: 'Root',
    children: [
      {
        name: 'Documents',
        children: [
          { name: 'report.pdf', size: 2500 },
          { name: 'presentation.pptx', size: 4800 },
        ],
      },
      {
        name: 'Pictures',
        children: [
          { name: 'vacation.jpg', size: 3200 },
          {
            name: 'Family',
            children: [
              { name: 'birthday.jpg', size: 1800 },
              { name: 'wedding.jpg', size: 4200 },
            ],
          },
        ],
      },
      { name: 'README.txt', size: 800 },
    ],
  };
  console.log(getSize('Family', dir));

  // 10、计算两个大数相加
  const addBigNum = (num1, num2) => {
    let str1 = num1.toString();
    let str2 = num2.toString();
    const maxLength = Math.max(str1.length, str2.length);
    str1 = str1.padStart(maxLength, '0');
    str2 = str2.padStart(maxLength, '0');

    let result = ''; // 使用数组拼接，每次拼接上下一位结果（从后往前）
    let carry = 0; // 计算进位

    // 从最低位开始逐层计算到第二位
    for (let i = maxLength - 1; i > 0; i--) {
      // 转化对应位置为10进制数字
      const digit1 = parseInt(str1[i], 10);
      const digit2 = parseInt(str2[i], 10);
      const sum = digit1 + digit2 + carry;
      carry = Math.floor(sum / 10);
      result = (sum % 10) + result;
    }
    // 最大位数相加时
    const digit1 = parseInt(str1[0], 10);
    const digit2 = parseInt(str2[0], 10);
    const last = carry + digit1 + digit2;
    return last + result;
  };
  console.log(addBigNum(9007199254740991, 1234567899999999999));
  return (
    <div>
      <div>1、选择k次数组：{roArr}</div>
      <div>2、找到1-10000中的对称数字：{symmetryNumber()}</div>
      <div>3、将数组中0移到数组末尾{afterZeroFn3([1, 0, 2, 0, 0, 1, 3])}</div>
      <div>4、数字逆转成字符串{reverseNumber2(234)}</div>
      <div>5、定时函数：{timeFunction(add, 1000, 5000, 3)}</div>
      <div></div>
    </div>
  );
}
